using System;
using System.Collections.Generic;
using SpreadsheetGear;
using Sustainalytics.Utils.Validation.Interfaces;

namespace Sustainalytics.Portfolios.BL
{
    public class PortfolioWorksheetValidator : IValidator<IWorksheet>
    {
        public bool IsValid(IWorksheet entity)
        {
            return Validate(entity);
        }

        public ICollection<string> BrokenRules(IWorksheet entity)
        {
            return Validate(entity) == true ? new[] {string.Empty} : new[] {"Not valid template!"};
        }


        private bool Validate(IWorksheet worksheetPortfolio)
        {
            if (worksheetPortfolio == null)
            {
                return false;
            }

            double value;
            if (worksheetPortfolio.Cells[0, 0] == null || worksheetPortfolio.Cells[1, 1] == null ||
                worksheetPortfolio.Cells[0, 1] == null
                ||
                (!string.Equals(worksheetPortfolio.Cells[0, 0].Text.Trim(), "Security name",
                    StringComparison.InvariantCultureIgnoreCase))
                ||
                !string.Equals(worksheetPortfolio.Cells[0, 1].Text.Trim(), "Security ID (required)",
                    StringComparison.InvariantCultureIgnoreCase)
                ||
                (
                    string.Equals(worksheetPortfolio.Cells[0, 2].Text.Trim(), "Security Weight", StringComparison.InvariantCultureIgnoreCase)
                    && worksheetPortfolio.Cells[1, 2].Text != string.Empty
                    && !Double.TryParse(worksheetPortfolio.Cells[1, 2].Text, out value)
                )
            )    
            {
                return false;
            }
            return true;
        }
    }
}